/*
 * @Author: your name
 * @Date: 2021-12-22 17:13:41
 * @LastEditTime: 2021-12-22 17:18:14
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \main-vue\src\singleSpa.js
 */
import {registerApplication,start} from "single-spa"
import store from './store'
async function loadScript(url){
  return new Promise((resolve,reject)=>{
    let script = document.createElement("script")
    script.src = url
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}
function loadApp(url, globalVar) {
    // 支持远程加载子应用
    return async () => {
      await loadScript(url + '/js/chunk-vendors.js')
      await loadScript(url + '/js/app.js')
      // 这里的return很重要，需要从这个全局对象中拿到子应用暴露出来的生命周期函数
      return window[globalVar]
    }
  }
  const apps = [
    {
      // 子应用名称
      name: 'app1',
      // 子应用加载函数，是一个promise
      app: loadApp('http://localhost:9974', 'child1'),
      // 当路由满足条件时（返回true），激活（挂载）子应用
      activeWhen: location => location.pathname.startsWith('/child1'),
      // 传递给子应用的对象
      customProps: {
          data:store
      }
    },
    {
      name: 'app2',
      app: loadApp('http://localhost:9975', 'child2'),
      activeWhen: location => location.pathname.startsWith('/child2'),
      customProps: {
        data:store
      }
    },
  ]
  
  // 注册子应用
  for (let i = apps.length - 1; i >= 0; i--) {
    registerApplication(apps[i])
  }
  start()